<!--
  * 代理商通道表
  *
  * @Author:    zwd
  * @Date:      2025-01-23 04:08:26
-->
<template>
  <a-modal
    :title="props.operateType == 'view' ? '查看费率' : '设置费率'"
    :width="800"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
    <a-table :columns="columns" :dataSource="rateData" :pagination="false" bordered>
      <template #bodyCell="{ column, record }">
        <!-- <template v-if="column.dataIndex === 'onlineRate'">
          <a-input-number
            v-model:value="record.onlineRate"
            :min="0"
            :max="100"
            :step="0.01"
            :disabled="form.defaultRates"
            style="width: 100%"
            :placeholder="form.defaultRates ? '使用默认' : ''"
            @change="validatorOnlineRate(record)"
          />
        </template>
        <template v-if="column.dataIndex === 'offlineRate'">
          <a-input-number
            v-model:value="record.offlineRate"
            :min="0"
            :max="100"
            :step="0.01"
            :disabled="form.defaultRates"
            style="width: 100%"
            :placeholder="form.defaultRates ? '使用默认' : ''"
            @change="validatorOfflineRate(record)"
          />
        </template> -->

        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showForm(record, props.apiType == 'agent' ? 'update' : 'view')" type="link">
              {{ props.operateType == 'view' ? '查看' : '设置' }}
            </a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="fetchChannelData"
        @showSizeChange="fetchChannelData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!--<div class="rate-note">-->
    <!--  <a-checkbox v-model:checked="form.defaultRates">默认通道参数</a-checkbox>-->
    <!--  <div class="note-text">注意：默认通道参数方便统一默认数值（避免重复填写）</div>-->
    <!--</div>-->

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <!-- <a-button type="primary" @click="onSubmit" v-if="level !== 2">保存</a-button> -->
      </a-space>
    </template>
  </a-modal>
  <rateForm ref="rateFormRef" @reloadList="rateFormOk" />
</template>
<script setup>
  import { nextTick, reactive, ref, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const.js'
  import { agentPayconfigPage, agentPayconfigSetRates } from '/@/api/business/b-agent/agent/agent-payconfig-api'
  import { merchantApi } from '/@/api/business/b-agent/merchant/merchant-api'
  import rateForm from '/@/components/business/comment/rate-form.vue'
  import { selectDictLabel } from '/@/utils/common'
  import {
    CHARGE_TYPE, //计费模式
  } from '/@/constants/dict'

  // ------------------------ 事件 ------------------------
  const props = defineProps({
    apiType: { type: String, default: 'agent' },
    operateType: { type: String, default: 'update' },
  })

  const emits = defineEmits(['reloadList'])

  const apiSource = {
    list: (data) => {
      if (props.apiType == 'agent') {
        let params = {
          ...data,
          agentId: data.id,
        }
        return agentPayconfigPage(params)
      }
      if (props.apiType == 'merchant') return merchantApi.ratePage(data)
    },
    findRate: (data) => {
      if (props.apiType == 'agent') return {}
      if (props.apiType == 'merchant') {
        let params = {
          ...data,
          merchantId: form.merchantId,
        }
        return merchantApi.findRate(params)
      }
    },
  }

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false)

  const total = ref(0)
  const queryFormState = {
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })

  const thisAgentId = ref()

  async function fetchChannelData(rowData) {
    try {
      const params = {
        pageNo: queryForm.pageNo,
        pageSize: queryForm.pageSize,
        id: thisAgentId.value,
        statusFlag: true,
      }
      const response = await apiSource.list(params)
      total.value = response.total
      return response.data.map((item) => ({
        ...item,
        onlineCost: item.costOnlineRate,
        offlineCost: item.costOfflineRate,
        onlineRate: item.agentOnlineRate,
        offlineRate: item.agentOfflineRate,
        // onlineRate: form.defaultRates ? item.dAgentOnlineRate : item.agentOnlineRate,
        // offlineRate: form.defaultRates ? item.dAgentOfflineRate : item.agentOfflineRate,
      }))
    } catch (err) {
      smartSentry.captureError(err)
      message.error('获取通道数据失败')
      return []
    }
  }

  function show(rowData) {
    Object.assign(form, formDefault)
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData)
    }
    thisAgentId.value = rowData?.id
    // form.defaultRates = rowData.defaultedFlag
    fetchChannelData(rowData).then((data) => {
      rateData.value = data.map((item) => ({
        ...item,
        onlineCost: item.onlineCost,
        offlineCost: item.offlineCost,
        onlineRate: item.onlineRate || '', // 如果没有线上费率，默认为空字符串
        offlineRate: item.offlineRate || '', // 如果没有线下费率，默认为空字符串
      }))
    })

    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    // defaultRates: false,
  }

  let form = reactive({ ...formDefault })

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      align: 'center',
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
    },
    {
      title: '通道名称',
      dataIndex: 'channelName',
    },
    {
      title: '计费模式',
      dataIndex: 'chargeType',
      customRender: ({ text }) => {
        return selectDictLabel(CHARGE_TYPE, text)
      },
    },
    {
      title: '设置费率',
      dataIndex: 'action',
      fixed: 'right',
      width: 90,
    },
    // {
    //   title: '线上成本',
    //   dataIndex: 'onlineCost',
    //   width: 120,
    // },
    // {
    //   title: '线下成本',
    //   dataIndex: 'offlineCost',
    //   width: 120,
    // },
    // {
    //   title: '线上费率',
    //   dataIndex: 'onlineRate',
    // },
    // {
    //   title: '线下费率',
    //   dataIndex: 'offlineRate',
    // },
  ]

  // 费率数据
  const rateData = ref([
    {
      channelId: 1,
      channelName: '支付宝',
      onlineCost: 0.25,
      offlineCost: 0.25,
      onlineRate: '',
      offlineRate: '',
    },
    {
      channelId: 2,
      channelName: '微信',
      onlineCost: 0.25,
      offlineCost: 0.25,
      onlineRate: '',
      offlineRate: '',
    },
  ])

  // 点击确定，验证表单
  async function onSubmit(data) {
    try {
      // if (form.defaultRates) {
      //   save()
      //   return
      // }

      // 验证费率输入
      // const invalidRate = [data].some((item) => {
      //   return (
      //     item.onlineRate === '' ||
      //     item.offlineRate === '' ||
      //     item.onlineRate < 0 ||
      //     item.onlineRate > 100 ||
      //     item.onlineRate < item.onlineCost ||
      //     item.offlineRate < 0 ||
      //     item.offlineRate > 100 ||
      //     item.offlineRate < item.offlineCost
      //   )
      // })

      // if (invalidRate) {
      //   message.error('请输入有效的费率（0-100之间）且费率不能小于成本')
      //   return
      // }

      save(data)
    } catch (err) {
      message.error('参数验证错误，请仔细填写数据!')
    }
  }

  // 新建、编辑API
  async function save(data) {
    SmartLoading.show()
    try {
      const param = {
        ...form,
        agentId: form.id,
        // defaultedFlag: form.defaultRates,
        agentRates: [data].map((item) => ({
          ...item,
          // channelId: item.channelId,
          // agentOnlineRate: item.agentOnlineRate,
          // agentOfflineRate: item.agentOfflineRate,
          // agentOnlineRate: form.defaultRates ? item.dAgentOnlineRate : item.onlineRate,
          // agentOfflineRate: form.defaultRates ? item.dAgentOfflineRate : item.offlineRate,
        })),
      }
      await agentPayconfigSetRates(param)
      message.success('费率设置成功')
      show(form)
      emits('reloadList')
      // onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  const validatorOnlineRate = (record) => {
    if (record.onlineRate < record.onlineRateCp) {
      record.onlineRate = undefined
    }
  }

  // 获取单条费率数据
  const getRate = async (data) => {
    try {
      const res = await apiSource.findRate(data)
      if (res.code !== 200) {
        return {}
      }
      return {
        agentOfflineRate: res.data?.offlineRate,
        agentOnlineRate: res.data?.onlineRate,
      }
    } catch (error) {
      console.log(error)
    }
  }
  // 设置费率
  const rateFormRef = ref()

  async function showForm(data, type) {
    let res = await getRate({
      ...data,
      id: thisAgentId.value,
    })
    rateFormRef?.value.show({ ...data, ...res }, type, props.apiType)
  }

  function rateFormOk(data) {
    // console.log('data==>', data)
    onSubmit(data)
  }

  // 设置费率

  // const changeDefaultRates = (val) => {
  //   console.log('form.defaultRates==>', form.defaultRates)
  // }
  // 监听默认参数开关变化
  // watch(
  //   () => form.defaultRates,
  //   async (newVal) => {
  //     // 重新获取数据并回填
  //     const data = await fetchChannelData(form)
  //     rateData.value = data.map((item) => ({
  //       ...item,
  //       onlineRate: newVal ? null : item.onlineRate,
  //       offlineRate: newVal ? null : item.offlineRate,
  //     }))
  //   },
  // )

  function onClose() {
    Object.assign(form, formDefault)
    visibleFlag.value = false
  }

  defineExpose({
    show,
  })
</script>

<style scoped>
  .ant-descriptions {
    margin-bottom: 20px;
  }

  .rate-note {
    margin-top: 16px;
  }

  .note-text {
    color: #ff7f00;
    margin-top: 8px;
  }

  .ant-table-cell {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .custom-span {
    display: inline-block;
    width: 100%; /* 与输入框宽度一致 */
    text-align: center;
    padding: 0 4px; /* 与输入框的内边距一致 */
  }
</style>
